package com.fruitsales.common;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.fruitsales.perm.service.PermService;
import com.fruitsales.user.service.userService;

/**
 * Shiro 核心Realm�?
 * 
 * @author Administrator
 *
 */

public class ShiroRealm extends AuthorizingRealm {
	@Autowired
	private userService userService;
	@Autowired
	private PermService permService;

	/**
	 * 加载当前用户的角色和权限信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection PrincipalCollection) {
	/*	System.out.println("用户权限验证");*/

		String LoginName = (String) getAvailablePrincipal(PrincipalCollection);

		System.out.println(LoginName + "用户权限验证");
		// 储存当前用户的角色和权限的对象?
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		// 设置当前用户的角色?
		HashSet<String> roleSet = new HashSet<>();
		List<Map<String, Object>> list = permService.queryRole(LoginName);

		for (Map map : list) {

			roleSet.add((String) map.get("role_name"));
		/*	System.out.println(map.get("role_name"));*/

		}
		info.setRoles(roleSet);

		// 设置当前用户的角色?
		HashSet<String> permSet = new HashSet<>();
		List<Map<String, Object>> list2 = permService.queryPerm(LoginName);

		for (Map map : list2) {

			permSet.add((String) map.get("perm_name"));
			/*System.out.println(map.get("perm_name"));*/

		}
		info.setStringPermissions(permSet);

		return info;
	}

	/**
	 * 用户登录验证(在登录时会自动回调?)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {

		/*System.out.println("用户登录验证被调用?");*/

		// 获得用户名和密码数据
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

		String LoginName = token.getUsername();
		String Pwd = String.valueOf(token.getPassword());

		int result = userService.checkLogin(LoginName, Pwd);

		if (result == -1) {
			throw new UnknownAccountException();
		} else if (result == 1) {
			// 密码不存在?
			throw new IncorrectCredentialsException();
		} else {
			// 登录成功
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(LoginName, Pwd.toCharArray(), getName());

			return info;
		}

	}

}
